package com.budwk.app.sqfwV2.generator.centuryCitySecurity.pdf;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BasePdfParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.enums.CenturyCitySafePlaceTypeEnum;
import com.budwk.app.sqfwV2.enums.HiddenDangerEnum;
import com.budwk.app.sqfwV2.enums.SafetyCheckV2Enums;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.deepoove.poi.data.PictureRenderData;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 本代码由代码生成器生成，版本号1.0
 */
public class SafetyCheckPdfGenerater extends BaseTemplatePdfGenerator {


    private String templateName;


    public SafetyCheckPdfGenerater() {
    }

    public SafetyCheckPdfGenerater(String templateName, String index) {
        this.templateName = templateName;
        super.setFileIdentity(index);
    }


    /**
     * 判断使用使用这个generator生成pdf
     *
     * @param pdfDTO 创建pdf数据素材
     * @return 结果
     */
    @Override
    public boolean pdfCreateConditionCheck(SqfwPdfCreateCommonBO pdfDTO) {
        return true;
    }

    @Override
    public String getTemplateName() {
        return this.templateName;
    }

    @Override
    public void customerPopularPdfParam(Map<String, Object> paramMap, SqfwPdfCreateCommonBO commonParam) {
        // 在这里对一些数据进行填充 进行复杂的业务代码逻辑
        BasePdfParamDTO basePdfParam = commonParam.getBasePdfParamDTO();
        SafeCheckTaskPdfDTO pdfDTO = JSONObject.parseObject(JSONObject.toJSONString(commonParam.getAbstractCustomerPdfCreateField()), SafeCheckTaskPdfDTO.class);
        if (!basePdfParam.getCommunity().contains("社区")) {
            paramMap.put("community", StrFormatter.format("{}社区 ", basePdfParam.getCommunity()));
        } else {
            paramMap.put("community", StrFormatter.format("{} ", basePdfParam.getCommunity()));
        }
        paramMap.put("fillDate", DateUtil.format(basePdfParam.getFillDate(), DatePattern.CHINESE_DATE_FORMATTER));
        paramMap.put("createUserName", StrUtil.formatStr(basePdfParam.getCreateUserName()));
        paramMap.put("checkedUnitLeader", CommonFormOfficeUtils.addWordPicture(pdfDTO.getCheckedUnitLeader(), 2.0F));
        if (!ObjectUtils.isEmpty(pdfDTO.getDeadlineForRectification())) {
            long days = ChronoUnit.DAYS.between(DateUtil.toLocalDateTime(basePdfParam.getFillDate()), pdfDTO.getDeadlineForRectification());
            paramMap.put("deadlineForRectification", days + 1);
        }
        paramMap.put("transferToMarketSupervisionAndManagement", pdfDTO.getTransferToMarketSupervisionAndManagement());
        paramMap.put("otherHandlingSuggestions", pdfDTO.getOtherHandlingSuggestions());
        String address =pdfDTO.getAddress();
        if(StringUtils.isNotBlank(pdfDTO.getPlot())){
            if(StringUtils.isNotBlank(pdfDTO.getAddress())){
                address=String.format("%s(%s)",pdfDTO.getPlot(),pdfDTO.getAddress());
            }else{
                address =pdfDTO.getPlot();
            }
        }
        paramMap.put("address", address);


        //整改前
        List<Map<String, PictureRenderData>> images = new ArrayList<>();
        //整改后
        List<Map<String, PictureRenderData>> imagesLast = new ArrayList<>();
        //走访图片
        List<Map<String, PictureRenderData>> visitPicturesFileList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(pdfDTO.getHiddenDanger())) {
            List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOS = pdfDTO.getHiddenDanger();
            for (SafeCheckTaskParamDataDTO dataDTO : safeCheckTaskParamDataDTOS) {
                String key = dataDTO.getKey();
                //2024-04-03 九小场所-健康证问题特殊处理，入九小场所跟餐饮的key取反向
                if (HiddenDangerEnum.isHaveMedicalCertificate.getCode().equals(dataDTO.getRiskCode())) {
                    if (String.valueOf(SafetyCheckV2Enums.A.getCode()).equals(super.getFileIdentity())) {
                        key = key.equals("是") ? "否" : "是";
                    }
                }
                paramMap.put(StrFormatter.format("var{}", dataDTO.getRiskCode()), key);
                if (dataDTO.getRiskCode().equals(HiddenDangerEnum.isHaveMedicalCertificate.getCode())) {
                    paramMap.put("numberOfEmployees", dataDTO.getNumberOfEmployees());
                    paramMap.put("numberOfValidHealthCertificates", dataDTO.getNumberOfValidHealthCertificates());
                }
                if (dataDTO.getRiskCode().equals(HiddenDangerEnum.foodOtherInformation.getCode())) {
                    paramMap.put("foodOtherInformation", dataDTO.getFoodOtherInformation());
                }
                //int num = Integer.parseInt(dataDTO.getRiskCode());
                HiddenDangerEnum hiddenDangerEnum = HiddenDangerEnum.getHiddenDangerEnumByCode(dataDTO.getRiskCode());
                if (ObjectUtils.isEmpty(hiddenDangerEnum)) continue;
                //隐患图片
                if (cn.hutool.core.util.StrUtil.isNotBlank(dataDTO.getRiskImages())) {
                    if (super.getFileIdentity().equals(String.valueOf(SafetyCheckV2Enums.G.getCode())) || super.getFileIdentity().equals(String.valueOf(SafetyCheckV2Enums.K.getCode()))
                            || super.getFileIdentity().equals(String.valueOf(SafetyCheckV2Enums.L.getCode()))) {
                        //大于42的为九小场所-食品安全的
                        //if (num > 42) {
                        if (hiddenDangerEnum.getType().contains(CenturyCitySafePlaceTypeEnum.RESTAURANT.getCode()) || hiddenDangerEnum.getType().contains(CenturyCitySafePlaceTypeEnum.canteen.getCode())) {
                            Map<String, PictureRenderData> map = new HashMap<>();
                            map.put("pictures", CommonFormOfficeUtils.addWordPicture(dataDTO.getRiskImages().split(",")[0], 10.0F));
                            images.add(map);
                        }
                    } else {
                        //安全排查
                        if (hiddenDangerEnum.getType().contains(SupportBusinessTypeEnum.SAFE_CHECK.getCode())) {
                            //2024-04-03 九小场所-健康证问题特殊处理，正常情况下不显示健康证的图片
                            if (HiddenDangerEnum.isHaveMedicalCertificate.getCode().equals(dataDTO.getRiskCode()) && !hiddenDangerEnum.getFlag().equals(dataDTO.getKey())) {
                                continue;
                            }
                            Map<String, PictureRenderData> map = new HashMap<>();
                            map.put("pictures", CommonFormOfficeUtils.addWordPicture(dataDTO.getRiskImages().split(",")[0], 10.0F));
                            images.add(map);
                        }
                    }
                }
                //整改后图片
                if (cn.hutool.core.util.StrUtil.isNotBlank(dataDTO.getRectificationBackPhoto())) {
                    Map<String, PictureRenderData> map = new HashMap<>();
                    map.put("pictures", CommonFormOfficeUtils.addWordPicture(dataDTO.getRectificationBackPhoto().split(",")[0], 10.0F));
                    imagesLast.add(map);
                }

            }
            //走访图片
            if (cn.hutool.core.util.StrUtil.isNotBlank(pdfDTO.getVisitPicturesFileList())) {
                List<String> list = Arrays.asList(pdfDTO.getVisitPicturesFileList().split(","));
                for (String image : list) {
                    Map<String, PictureRenderData> map = new HashMap<>();
                    map.put("pictures", CommonFormOfficeUtils.addWordPicture(image, 10.0F));
                    visitPicturesFileList.add(map);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(pdfDTO.getOtherHiddenDangers())) {
            List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOS = pdfDTO.getOtherHiddenDangers();
            for (SafeCheckTaskParamDataDTO dataDTO : safeCheckTaskParamDataDTOS) {
                //隐患（整改前）图片
                if (cn.hutool.core.util.StrUtil.isNotBlank(dataDTO.getRiskImages())) {
                    //安全排查
                    Map<String, PictureRenderData> map = new HashMap<>();
                    map.put("pictures", CommonFormOfficeUtils.addWordPicture(dataDTO.getRiskImages().split(",")[0], 10.0F));
                    images.add(map);

                }
                //整改后图片
                if (cn.hutool.core.util.StrUtil.isNotBlank(dataDTO.getRectificationBackPhoto())) {
                    Map<String, PictureRenderData> map = new HashMap<>();
                    map.put("pictures", CommonFormOfficeUtils.addWordPicture(dataDTO.getRectificationBackPhoto().split(",")[0], 10.0F));
                    imagesLast.add(map);
                }
            }
        }
        String imagesNum = null;
        String imagesLastNum = null;
        String visitPicturesFileListNum = null;
        if (!images.isEmpty()) {
            imagesNum = String.format("附件： %s  %s 整改前照片", pdfDTO.getPlaceName(), DateUtil.format(basePdfParam.getFillDate(), DatePattern.CHINESE_DATE_FORMATTER));
        }
        if (!imagesLast.isEmpty()) {
            imagesLastNum = String.format("附件： %s  %s 整改后照片", pdfDTO.getPlaceName(), DateUtil.format(basePdfParam.getFillDate(), DatePattern.CHINESE_DATE_FORMATTER));
        }
        if (!visitPicturesFileList.isEmpty()) {
            visitPicturesFileListNum = String.format("附件： %s  %s 走访照片", pdfDTO.getPlaceName(), DateUtil.format(basePdfParam.getFillDate(), DatePattern.CHINESE_DATE_FORMATTER));
        }
        paramMap.put("images", images);
        paramMap.put("imagesLast", imagesLast);
        paramMap.put("imagesNum", imagesNum);
        paramMap.put("imagesLastNum", imagesLastNum);
        paramMap.put("visitPicturesFileListNum", visitPicturesFileListNum);
        paramMap.put("visitPicturesFileList", visitPicturesFileList);
        if (cn.hutool.core.util.StrUtil.isNotBlank(pdfDTO.getPlaceFireExtinguishersNumber())) {
            int num = Integer.parseInt(pdfDTO.getPlaceFireExtinguishersNumber());
            if (num > 0) {
                paramMap.put("var99", "是");
            } else {
                paramMap.put("var99", "否");
            }
        }
        if (super.getFileIdentity().equals("8")) {
            if (paramMap.get("var50").equals("是") && paramMap.get("var52").equals("是")) {
                paramMap.put("var96", "是");
            } else {
                paramMap.put("var96", "否");
            }
            if (paramMap.get("var51").equals("是") && paramMap.get("var87").equals("是")) {
                paramMap.put("var97", "是");
            } else {
                paramMap.put("var97", "否");
            }
            if (paramMap.get("var48").equals("是") && paramMap.get("var49").equals("是")) {
                paramMap.put("var98", "是");
            } else {
                paramMap.put("var98", "否");
            }

        }

    }

    private boolean getKey(String key) {
        return key.equals("true");
    }
}
